﻿#include "websocketserver.h"
#include <QDebug>

WebSocketServer::WebSocketServer(quint16 port,QObject *parent) : QObject(parent),
    m_webSocketServer(new QWebSocketServer(QStringLiteral("Test WebSocket Server"),
                                           QWebSocketServer::NonSecureMode, this))  // 创建一个非加密的 WebSocket 服务器
{
    if (m_webSocketServer->listen(QHostAddress::Any, port))  // 启动服务器监听指定端口
    {
        qDebug() << "WebSocket server started on port" << port;
        connect(m_webSocketServer, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection);  // 连接新客户端信号
    }
    else
    {
        qDebug() << "Failed to start WebSocket server!";
    }
}

WebSocketServer::~WebSocketServer()
{
    m_webSocketServer->close();  // 关闭服务器
    qDeleteAll(m_clients.begin(), m_clients.end());  // 删除所有客户端连接
}

void WebSocketServer::onNewConnection()
{
    QWebSocket *pSocket = m_webSocketServer->nextPendingConnection();  // 获取新的连接
    connect(pSocket, &QWebSocket::textMessageReceived, this, &WebSocketServer::processTextMessage);  // 处理收到的文本消息
    connect(pSocket, &QWebSocket::disconnected, this, &WebSocketServer::socketDisconnected);  // 客户端断开连接时调用

    m_clients << pSocket;  // 将客户端添加到列表中
    qDebug() << "New client connected:" << pSocket;
}

void WebSocketServer::processTextMessage(const QString &message)
{
    QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());  // 获取发送消息的客户端
    qDebug() << "Message received:" << message;

    // 回显消息给所有连接的客户端
    for (QWebSocket *client : qAsConst(m_clients))
    {
        if (client && client->isValid())  // 检查客户端是否有效
        {
            client->sendTextMessage(message);  // 发送消息给客户端
        }
    }
}

void WebSocketServer::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());  // 获取断开连接的客户端
    if (pClient)
    {
        m_clients.removeAll(pClient);  // 从客户端列表中移除
        pClient->deleteLater();  // 延迟删除
        qDebug() << "Client disconnected:" << pClient;
    }
}
